<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    :isDetail="false"
    :width="getIsMobile ? '95%':'80%'"
    @ok="handleSubmit"
  >
    <!-- <BasicForm @register="registerForm" /> -->
      <Tabs v-model:activeKey="activeKey">
        <TabPane
          v-for="item in tabsFormSchema"
          :key="item.key"
          v-bind="omit(item, ['Form', 'key'])"
        >
          <BasicForm @register="item.Form[0]">
            <template #attribute="{ model, field }">
              <GoodsAttr v-if="item.key=='tabs3'" :field="field" :model="model" />
            </template>
            <template #spec="{ model, field }">
              <SaleAttr v-if="item.key=='tabs1'" @success="successSku" :spec="model[field]" :skus="model['skus']"/>
            </template>
          </BasicForm>
        </TabPane>
      </Tabs>
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { ref,computed, unref, nextTick, reactive } from 'vue';
  import { useAppInject } from '@/hooks/web/useAppInject';
  import { Tabs } from 'ant-design-vue';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { useMessage } from '@/hooks/web/useMessage';
  import { omit } from 'lodash-es';
  import { deepMerge } from '@/utils';
  import { BasicForm, FormSchema, useForm, FormProps, UseFormReturnType } from '@/components/Form';
  import { goodsFormSchema, detailFormSchema, saleAttrFormSchema, goodsAttrFormSchema } from './goods.data';
  import { getDeptList } from '@/api/demo/system';
  import GoodsAttr from './GoodsAttr.vue';
  import SaleAttr from './SaleAttr.vue';

  defineOptions({ name: 'TabsFormDemo' });

  const { getIsMobile } = useAppInject();
  const emit = defineEmits(['success', 'register']);
  const state = reactive({addSkus:[]});
  const isUpdate = ref(true);
  const rowId = ref('');
  const { createMessage } = useMessage();
  const activeKey = ref('tabs0');
  const tabsFormSchema: TabsFormType[] = [];

  // 公共属性
  const baseFormConfig: Partial<FormProps> = {
    showActionButtonGroup: false,
    labelWidth: 100,
    baseColProps: { span: 24 },
  };
  // // 为每个字段模拟默认值, { tabs1: { field1: '', field2: '' }, tabs2: { field1: '' }, ... }
  // const mockDefaultValue: Recordable = {};

  // 模拟5个标签页
  var sa = [{name:'基本信息',sc:goodsFormSchema},{name:"销售设置",sc: saleAttrFormSchema},{name:"商品详情",sc:detailFormSchema},{name:"商品属性",sc: goodsAttrFormSchema}];
  for (let i = 0; i < sa.length; ++i) {
    let schemas: FormSchema[] = sa[i].sc;
    tabsFormSchema.push({
      key: `tabs${i}`,
      tab: sa[i].name,
      forceRender: true,
      Form: useForm(Object.assign({ schemas }, baseFormConfig) as FormProps),
    });
  }


  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    handleReset();
    activeKey.value = 'tabs0';
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      // data.record.spec= [{name:'颜色',value:['黑','白']},{name:'尺码',value:['M','L']}];
      // data.record.skus = [ { "尺码": "M", "颜色": "黑",price:12.03, skuId: 11, goodsId:11 }, { "尺码": "L", "颜色": "黑" }, { "尺码": "L", "颜色": "白" },{ "尺码": "M", "颜色": "白" ,price:22.03, skuId: 22, goodsId:22} ];  
      
      nextTick(() => {
        handleSetValues({
          ...data.record,
        });
      })
    } 

    const treeData = await getDeptList();

    const { updateSchema } = tabsFormSchema[0].Form[1];

    updateSchema([
      // {
      //   field: 'pwd',
      //   show: !unref(isUpdate),
      // },
      {
        field: 'dept',
        componentProps: { treeData },
      },
    ]);
  });

  const TabPane = Tabs.TabPane;
  type TabsFormType = {
    key: string;
    tab: string;
    forceRender?: boolean;
    Form: UseFormReturnType;
  };

  function successSku(addSkus) {
    state.addSkus = addSkus;
  }
  
  async function handleReset() {
    for (const item of tabsFormSchema) {
      const { resetFields } = item.Form[1];
      await resetFields();
    }
  }

  async function handleSubmit() {
    let lastKey = '';
    setDrawerProps({ confirmLoading: true });
    try {
      let values: Recordable = {};
      for (const item of tabsFormSchema) {
        lastKey = item.key;
        const { validate, getFieldsValue } = item.Form[1];
        await validate();
        // 表单已支持多级key
        values = deepMerge(values, getFieldsValue());
      }
      if(state.addSkus) {
        values = deepMerge(values, {skus:state.addSkus});
      }
      console.log('submit values: ',JSON.stringify( values));
      createMessage.success('提交成功！请打开控制台查看');
      closeDrawer();
    } catch (e) {
      // 验证失败或出错，切换到对应标签页
      activeKey.value = lastKey;
      console.error(e);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
  const getTitle = computed(() => (!unref(isUpdate) ? '商品发布' : '商品资讯'));

  async function handleSetValues(mockDefaultValue) {
    // console.log('mockDefaultValue',JSON.stringify(mockDefaultValue))
    for (const item of tabsFormSchema) {
      const { setFieldsValue } = item.Form[1];
      await setFieldsValue(mockDefaultValue);
    }
  } 
</script>
